package service

import (
	"context"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"strconv"
	"time"
	"video-srv/basic/config"
	__ "video-srv/basic/proto/rpc"
	"video-srv/handler/model"
	"video-srv/pkg"
)

type VideoServer struct {
	__.UnimplementedVideoServer
}

func (s *VideoServer) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	smsCode, _ := config.Rdb.Get(config.Ctx, "smsCode_"+in.Phone).Result()
	if smsCode != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	user := model.User{
		Phone:     in.Phone,
		Password:  in.Password,
		Username:  in.Username,
		AvatarUrl: uuid.NewString() + "png",
	}
	err := user.Register(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.RegisterResp{
		UserId: int64(user.ID),
	}, nil
}

func (s *VideoServer) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	var user model.User
	err := user.IsPhone(config.DB, in.Phone)
	if err != nil {
		return nil, err
	}
	smsCode, _ := config.Rdb.Get(config.Ctx, "smsCode_"+in.Phone).Result()
	if smsCode != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	return &__.LoginResp{
		UserId: int64(user.ID),
	}, nil
}

func (s *VideoServer) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	timeCount, _ := config.Rdb.Get(config.Ctx, "smsCodeTime_"+in.Phone).Int()
	if timeCount >= 5 {
		return nil, fmt.Errorf("同一手机号每天最多请求验证码5次")
	}
	code := rand.Intn(900000) + 100000
	sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	if err != nil {
		return nil, err
	}
	if sms.Code != 2 {
		return nil, err
	}
	config.Rdb.Set(config.Ctx, "smsCode_"+in.Phone, code, time.Minute*5)
	config.Rdb.Incr(config.Ctx, "smsCodeTime_"+in.Phone)
	config.Rdb.Expire(config.Ctx, "smsCodeTime_"+in.Phone, time.Hour*24)
	rab := NewRabbitMQSimple("sendSms_code_" + in.Phone)
	rab.PublishSimple(strconv.Itoa(code))
	log := model.Log{
		NewRabbitMQSimple: rab.QueueName,
		SmsCode:           code,
	}
	err = log.Log(config.DB)
	if err != nil {
		return nil, err
	}
	return &__.SendSmsResp{}, nil
}
